<template>
  <div class="role-list-container">
    <el-card>
      <!-- 工具栏 -->
      <el-row :gutter="10" class="mb-4">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" @click="handleBatchDelete">批量删除</el-button>
        </el-col>
      </el-row>

  <!--添加角色的对话框-->
  <el-dialog title="添加角色" v-model="roleDialogVisible" style="width:500px;padding:50px;">
    <el-form :model="newRoles" ref="formRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="newRoles.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDes" label-width="80px">
          <el-input v-model="newRoles.roleDes" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addRole">确定</el-button>
        </span>
      </template>
    </el-dialog>
      <!-- 表格 -->
      <el-table
        :data="roles"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="roleId" label="角色编号" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
        <el-table-column prop="roleDes" label="角色描述" align="center"></el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">修改</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.roleId)">删除</el-button>
            <el-button size="small" type="warning" @click="openAssignPermissionDrawer(row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--修改角色的对话框-->
  <el-dialog title="修改角色信息" v-model="roleUpdateDialogVisible" style="width:500px;padding:50px;">
    <el-form :model="newRoles" ref="formRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="newRoles.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDes" label-width="80px">
          <el-input v-model="newRoles.roleDes" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="roleUpdateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateRoles">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配权限抽屉 -->
    <el-drawer
      v-model="assignPermissionDrawerVisible"
      title="分配权限"
      direction="rtl"
      size="30%"
    >
      <div class="assign-permission-content">
        <el-tree
          :data="permissionTreeData"
          node-key="id"
          show-checkbox
          default-expand-all
          :props="defaultProps"
          ref="treeRef"
        />
        <div class="drawer-footer">
          <el-button @click="assignPermissionDrawerVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermissions">保存权限</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { onMounted,ref,reactive } from 'vue';
import { ElMessage, ElMessageBox, ElTree } from 'element-plus';
// 角色功能
import { getRoleList,insertRole,deleteRole,updateRole,deleteRoles,getPermissionId,getPerm } from '../../api/role'
// 权限显示
import {getPermission} from '../../api/permission'
// 角色数据
const roles = ref([]);
const role =reactive({
  currentPage:1,
  pageSize:10
})
// 挂载数据
onMounted(() => {
  fetchRoles()

  loadPermission()
})

// 获取数据
const fetchRoles = async()=>{
   // 获取到数据
    let response = await getRoleList(role)
    roles.value = response.data.data
}

// 响应的数据格式
let newRoles = reactive({
  roleName:'',
  roleDes:''
})
// 情况对话框
const clear = ()=>{
  newRoles = reactive({
  roleName:'',
  roleDes:''
 })
}
// 添加角色的对话框
const roleDialogVisible = ref(false)
// 修改角色的对话框
const roleUpdateDialogVisible = ref(false)
// 显示添加用户的对话框
const handleAdd = async () => {
  clear()
  roleDialogVisible.value = true
}
// 添加操作具体实现
const addRole = async ()=>{
  try{
    let response = await insertRole(newRoles)
    ElMessage.success(response.message)
    roleDialogVisible.value = false
    fetchRoles()
  }catch(error){
    ElMessage.error("添加失败")
  }
}

//  修改，显示对话框并回显数据
const handleEdit = async(role)=>{
  roleUpdateDialogVisible.value = true
  newRoles = role 
}
// 修改
const updateRoles = async ()=>{
  try{
    let response = await updateRole(newRoles)
    ElMessage.success(response.message)
    roleUpdateDialogVisible.value = false
  }catch(error){
    ElMessage.error("修改失败")
  }
}

// 删除
const handleDelete = async (id) => {
  if(id){
    ElMessageBox.confirm(`确认删除本条角色吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: '警告'
    }).then( async ()=> {let response = await deleteRole(id)
      ElMessage.success(response.message)
      await fetchRoles()
    })
  }
}
// 批量删除
// 选中行处理  数组
const selectedIds = ref([]);  
// 将选中行的编号交于selectIds数组
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.roleId);
}

const handleBatchDelete = () => {
  if (!selectedIds.value.length) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条角色吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then( async () => {
    //roles.value = roles.value.filter(r => !selectedIds.value.includes(r.roleId));
    // 调用接口进行批量删除
    let response = await deleteRoles(selectedIds.value)
    selectedIds.value = [];
    ElMessage.success(response.message || '批量删除成功');
    fetchRoles()
  })
}


// 权限
// 权限树的数据（示例）
const permissionTreeData = ref([]);
// 当前编辑的角色 ID
const currentRoleId = ref(null);
// 控制抽屉是否显示
const assignPermissionDrawerVisible = ref(false);

// 获取所有权限
const loadPermission = async ()=>{
  let response = await getPermission()
  permissionTreeData.value = response.data
}


// 树配置
const defaultProps = {
  children: 'children',
  label: 'label'
};

// el-tree 的引用
const treeRef = ref();

// 打开分配权限抽屉并加载已有权限
const openAssignPermissionDrawer = async (row) => {
  currentRoleId.value = row.roleId
  assignPermissionDrawerVisible.value = true
  let response = await getPermissionId(row.roleId)
  treeRef.value.setCheckedKeys(response.data)

};

// 提交权限
const submitPermissions = async() => {
  const checkedKeys = treeRef.value.getCheckedKeys();
  //ElMessage.success(`角色 ${currentRoleId.value} 已保存权限：${checkedKeys.join(',')}`);
  let response = await getPerm(currentRoleId.value,checkedKeys)
  ElMessage.success(response.message)
  assignPermissionDrawerVisible.value = false;
};
</script>


<style scoped>
.assign-permission-content {
  padding: 20px;
}

.drawer-footer {
  margin-top: 20px;
  text-align: right;
}
.mb-4 {
  margin-bottom: 1rem;
}
</style>